package com.test.application.lua;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;

@Component
@RequiredArgsConstructor
public class MyInterceptor implements HandlerInterceptor {

    private final RedisScript<Long> redisLimitScript;

    private final RedisTemplate<String, Object> redisTemplate;

    //脚本concurrency.lua
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        Long current = redisTemplate.execute(redisLimitScript, new ArrayList<>(), System.currentTimeMillis() + "", 1000 + "", System.currentTimeMillis() - 1000 + "", 10 + "");
//        LocalDateTime now = LocalDateTime.now();
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
//        String format = now.format(dateTimeFormatter);
//        System.out.println("当前时间" + format + " 当前并发数：" + current);
//        return HandlerInterceptor.super.preHandle(request, response, handler);
//    }

    //脚本limit.lua
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String key = "Limit_a8d997ca27904e60b07c70056757a57d";
        long ttl = 120000;
        long now = System.currentTimeMillis();
        long expire = now - ttl;
        long max = 10;
        Long current = redisTemplate.execute(redisLimitScript, Collections.singletonList(key), now + "", ttl + "", expire + "", max + "");
        if (current == 0) {
            throw new RuntimeException("达到限流大小");
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
